
<!-- 校区管理 -->
<template>
  <div class="school_management_container">
    <div class="search_box">
      <!-- <el-button type="primary" class="fl" @click="showPopup">新增</el-button> -->
      <div v-if="powerList.add.show == 1" class="btn btn_add" @click="showPopup('ruleForm')">
        <i class="el-icon-plus"></i>
        <span class="btn_txt">新建</span>
      </div>
      <div  class="fr" >
        <el-input placeholder="请输入校区名称/编号" size="small" v-model="searchValue" @keyup.enter.native="searchData(searchValue)">
          <div slot="append" class="btn_search" @click="searchData(searchValue)">查询</div>
        </el-input>
      </div>
      <div class="clear"></div>
    </div>
    <div class="table_box">
      <adminTable :tableHead="tableHead" :tableData="tableData"></adminTable>
      <el-pagination
        class="pagination"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="page.curPage"
        :page-sizes="[10, 20, 50]"
        :page-size="page.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="page.totalRows">
      </el-pagination>
    </div>


    <transition name="el-fade-in-linear">
      <div class="popup-container" v-show="popupState.showStatus">
        <div class="popup">
          <i class="el-icon-error icon_close" @click="popupState.showStatus = false"></i>
          <div class="title">{{popupState.popupName}}</div>

          <div class="content">
            <el-form :model="formData" ref="ruleForm" :rules="rules" label-position="left" :readonly="checkStatus" style=""
              label-width="100px" class="form">
              <div style="overflow:hidden">
                <el-form-item label="编号 : " size="small" class="fl not_must">
                  <el-input v-model="formData.schoolCode" readonly autocomplete="off" ></el-input>
                </el-form-item>
                <el-form-item label="校区名称 : " prop="schoolName" size="small" class="fl">
                  <el-input v-model="formData.schoolName" autocomplete="off" placeholder="请输入校区名称"></el-input>
                </el-form-item>
                
                <el-form-item label="联系电话 : " prop="phone" size="small" class="fl no_margin_right">
                  <el-input  v-model.number="formData.phone"  maxlength="11" autocomplete="off" placeholder="请输入联系电话"></el-input>
                </el-form-item>

                <div class="clear"></div>

                <el-form-item label="所在省份 : " prop="provinceCode" size="small" class="fl">
                  <el-select v-model="formData.provinceCode" placeholder="请选择校区所在省份" @change="entCity_change"
                    >
                    <el-option v-for="(item,key) in addressOption" :key="key" :value="item.id" :label="item.lable">
                    </el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="所在城市 : " prop="cityCode" size="small"  class="fl">
                  <el-select v-model="formData.cityCode" placeholder="请选择校区所在城市" @change="entCity_change2"
                    >
                    <el-option v-for="(item,key) in entCity_arr" :key="key" :label="item.lable" :value="item.id">
                    </el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="所在区县 : " prop="countyCode" size="small" class="fl no_margin_right">
                  <el-select v-model="formData.countyCode" placeholder="请选择校区所在地区" @change="entCity_change3"
                    >
                    <el-option v-for="(item , key) in entCity_arr2" :key="key" :label="item.lable" :value="item.id">
                    </el-option>
                  </el-select>
                </el-form-item>

                <div class="clear"></div>

                <el-form-item label="面积(m²) : " prop="schoolArea" size="small" class="fl">
                  <el-input  v-model.number="formData.schoolArea" autocomplete="off" placeholder="请输入校区面积"></el-input>
                </el-form-item>
                <el-form-item label="员工数(人) : " prop="employeesNumber" size="small" class="fl">
                  <el-input  v-model.number="formData.employeesNumber" autocomplete="off" placeholder="请输入校区员工数量"></el-input>
                </el-form-item>

                <el-form-item label="类型 : " prop="schoolType" size="small" class="fl no_margin_right">
                  <el-select v-model="formData.schoolType" placeholder="请选择校区类型">
                    <el-option label="直营" value="1"></el-option>
                    <el-option label="加盟" value="2"></el-option>
                    <el-option label="合营" value="3"></el-option>
                  </el-select>
                </el-form-item>
                <div class="clear"></div>
                
                <el-form-item label="详细地址 : " prop="detailedAddress" size="small" style="width: 45%;" class="fl">
                  <el-input  v-model="formData.detailedAddress" autocomplete="off" placeholder="请输入校区详细地址"></el-input>
                </el-form-item>
                <div class="clear"></div>

                

              </div>

            </el-form>

            <div class="btn_box">
              <div class="btn btn_add" v-if="popupState.popupName == '新建校区'" @click="submitAdd('ruleForm')">
                <span class="btn_txt">保存</span>
              </div>

              <div class="btn btn_add" v-if="popupState.popupName == '编辑校区'" @click="submitEdit('ruleForm')">
                <span class="btn_txt">保存</span>
              </div>
            </div>

          </div>
        </div>
      </div>
    </transition>
  </div>
</template>


<style scoped>

</style>

<script>
import adminTable from '@/components/assembly/adminTable'

import {
  createNamespacedHelpers
} from "vuex";
let {
  mapState,
  mapGetters,
  mapMutations,
  mapActions
} = createNamespacedHelpers("schoolManagement");
export default {
  name: 'schoolManagement',
  data() {
    return {
      powerList: {
        add: {
          show: 0,
          menuId: '',
        }
      },
      jwtAuth: {},
      searchValue: '',
      checkStatus: false,
      schoolId: '',
      page: {
        curPage : 0,
        pageSize: 0,
        totalRows: 0,
      },
      formData: {
        schoolCode: '',
        schoolName: '',
        provinceName: '',
        provinceCode: '',
        cityName: '',
        cityCode: '',
        countyName: '',
        countyCode: '',
        detailedAddress: '',
        phone: '',
        schoolArea: '',
        employeesNumber: '',
        schoolType: '',
      },
      popupState: {
        showStatus: false,
        popupName: '新建校区',
      },
      tableHead: {
        // border: true,
        // order: true,
        operation_width: '150px',
        setFunction: [
          {
            showState: "0",
            hideKey: "showUpdate",
            fun: this.tableEdit,
            name: "编辑"
          },
          {
            showState: "0",
            hideKey: "showDelete",
            fun: this.tableDelete,
            name: "删除"
          },
        ],
        data: [
          {
            name: '编号',
            key: 'schoolCode',
            align: 'center',
            width: '60px;'
          },
          {
            name: "校区名称",
            key: "schoolName",
            align: "center",
            width: '125px;'
          },
          {
            name: "所在城市",
            key: "cityName",
            align: "center",
            width: '70px;'
          },
          {
            name: "所在区县",
            key: "countyName",
            align: "center",
            width: '70px;'
          },
          {
            name: "详细地址",
            key: "detailedAddress",
            align: "center"
          },
          {
            name: "联系电话",
            key: "phone",
            align: "center",
            width: '105px;'
          },
          {
            name: "面积",
            key: "schoolArea",
            align: "center",
            width: '50px;'
          },
          {
            name: "员工数",
            key: "employeesNumber",
            align: "center",
            width: '60px;'
          },
          {
            name: "类型",
            key: "schoolType",
            align: "center",
            filter: {
              1: '直营',
              2: '加盟',
              3: '合营',
            },
            width: '50px;'
          },
        ]
      },
      tableData: [],
      schoolList: [],
      schoolIdArr: [],
      
      addressOption: [],
      entCity_arr: {},
      entCity_arr2: {},
      rules: {
        schoolName: [
          { required: true, message: '请输入校区名称', trigger: 'blur' },
        ],
        provinceCode: [
          { required: true, message: '请选择校区所在省份', trigger: 'change' },
        ],
        cityCode: [
          { required: true, message: '请选择校区所在城市', trigger: 'change' },
        ],
        countyCode: [
          { required: true, message: '请选择校区所在区', trigger: 'change' },
        ],
        detailedAddress: [
          { required: true, message: '请输入校区详细地址', trigger: 'blur' },
        ],
        phone: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          {pattern: /^1[34578]\d{9}$/, message: '手机号格式错误'}
        ],
        schoolArea: [
          { required: true, message: '请输入校区面积', trigger: 'blur' },
          // { type: 'number', message: '类型错误，请输入数字', trigger: 'blur' }
        ],
        employeesNumber: [
          { required: true, message: '请输入校区员工数量', trigger: 'blur' },
          // { type: 'number', message: '类型错误，请输入数字', trigger: 'blur' }
        ],
        schoolType: [
          { required: true, message: '请选择校区类型', trigger: 'change' },
        ],
      }

    }
  },
  created() {
    this.jwtAuth = JSON.parse(sessionStorage.getItem('jwtAuth'));
    this.queryAllSchool();
    // this.initData();
    this.initCityData();
  },
  // watch: {
  //   mapPowerList: {
  //     handler(newName, oldName) {
  //     },
  //     immediate: true,
  //     deep: true
  //   }
  // },
  
  methods: {
    ...mapMutations([
      "updateInfo",
    ]),
    ...mapActions([
      "formGet",
      "post"
    ]),

    // 获取列表
    initData(searchValue) {
      // console.log(searchValue)
      searchValue = searchValue || this.searchValue || '';
      let data = {
        searchValue: searchValue,
        curPage: this.page.curPage,
        pageSize: this.page.pageSize,
      }

      data.accountId = this.jwtAuth.accountId;
      data.menuId = this.$route.name;
      data.schoolId = this.schoolIdArr
      this.post({
        API: 'selectBmSchoolPageList',
        data: data
      }).then(res => {
        this.tableData = res.data;
        if(res.buttons) {
          res.buttons.menuList[0].children.forEach(item => {
            if(item.label == '新建') {
              this.powerList.add.show = 1
              this.powerList.add.menuId = item.menuId
            }
            // console.log(this.powerList)
          })
        }

        res.data.forEach(item => {
          if(item.buttonMap) {
            let menuList = item.buttonMap.menuList[0].children
            menuList.forEach((menuItem, menuIndex) => {
              if(menuItem.menuId == '1611') {     // 编辑
                if(menuItem.isDisplay == 1) {
                  item.showUpdate = 1
                }else{
                  item.showUpdate = 0
                }
              }
              if(menuItem.menuId == '1612') {     // 删除
                if(menuItem.isDisplay == 1) {
                  item.showDelete = 1
                }else{
                  item.showDelete = 0
                }
              }
            })
          }
        })
        this.page = res.page;
      }).catch(err => {
        this.$message.error(err);
      })
    },


    queryAllSchool(btnId) {
      let accountId
      this.jwtAuth.schoolId == '' ? accountId = '' : accountId = this.jwtAuth.accountId
      
      this.post({    // 校区
        API: 'queryAllSchool',
        data: {
          accountId: accountId,
          menuId: btnId || this.$route.name,
          schoolIds: this.jwtAuth.schoolId.split(','),
        }
      }).then(res => {
        this.schoolList = res
        this.schoolIdArr = []
        this.schoolList.forEach(item => {
          this.schoolIdArr.push(item.schoolId)
        })
        this.initData();
      })
    },


    searchData(searchValue) {
      this.page.curPage = 1;
      this.initData(searchValue)
    },
    // 获取区县
    initCityData() {   
      this.formGet({
        API: "selectArea"
      })
      .then(res => {
        this.addressOption = res;
      })
      .catch(err => {
        this.$message.error(err);
      });
    },
    getSchoolCode() {
      this.post({
        API: 'getSchoolCode'
      }).then(res => {
        this.formData.schoolCode = res
        this.popupState = {
          showStatus: true,
          popupName: '新建校区',
        }
      }).catch(err => {
        this.$message.error(err);
      })
    },

    showPopup(formName) {
      this.$refs[formName].resetFields();   // 初始化
      this.getSchoolCode();
    },

    // 新增提交
    submitAdd(formName) {
      let data = this.formData;

      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.post({
            API: 'insert',
            data: data
          }).then(res => {
            console.log(res)
            if(res == 1) {
              this.$message.success('新建成功')
              this.initData();
              this.popupState.showStatus = false;
            }
          }).catch(err => {
            this.$message.error(err);
          })
        } else {
          // console.log('error submit!!');
          return false;
        }
      });

      
    },

    // 编辑提交
    submitEdit(rowData) {
      let data = this.formData
      data.schoolId = this.schoolId;

      this.$refs.ruleForm.validate((valid) => {
        if(valid) {
          this.post({
            API: 'update',
            data: data
          }).then(res => {
            this.$message.success('修改成功');
            this.initData();
            this.popupState.showStatus = false;
          }).catch(err => {
            this.$message.error(err);
          })
        }
      });
      
    },

    // 表格编辑 回显
    tableEdit(rowData) {
      this.$refs.ruleForm.resetFields();
      this.schoolId = rowData.row.schoolId;
      let data = {
        id: this.schoolId,
      }
      this.formGet({
        API: 'selectById',
        data: data
      }).then(res => {
        this.popupState = {
          popupName: '编辑校区',
          showStatus: true,
        }
        this.formData = res;
        this.formData.schoolType = this.formData.schoolType.toString();
        this.entCity_change(res.provinceCode, true);
        this.entCity_change2(res.cityCode, true);
        // this.entCity_change3(res.countyCode);
        
      }).catch(err => {
        // this.$message.error(err);
      })
    },



    // 表格删除
    tableDelete(rowData) {
      let schoolId = rowData.row.schoolId;
      let data = {
        id: schoolId,
      }

      this.$confirm('是否删除该校区?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.formGet({
          API: 'deleteById',
          data: data
        }).then(res => {
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
          this.initData();
        }).catch(err => {
          this.$message.error(err);
        })
        
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });          
      });

      
      
    },

    // 省市县三级联动
    entCity_change(e, bool) {
      if(!bool) {
        this.formData.cityCode = "";
        this.formData.countyCode = "";
      }
      let obj = {};
      obj = this.addressOption.filter(item => {
        return item.id === e;
      });
      this.entCity_arr = obj[0].children;
      if (this.entCity_arr.length == 1) {
        this.formData.cityCode = this.entCity_arr[0].id
        this.entCity_change2(this.entCity_arr[0].id)
      }
      this.formData.provinceId = obj[0].id;
      this.formData.provinceName = obj[0].lable;
    },
    entCity_change2(e, bool) {
      // if(!bool) {
      //   this.formData.countyCode = "";
      // }
      let obj = {};
      obj = this.entCity_arr.filter(item => {
        return item.id === e;
      });

      this.formData.cityName = obj[0].lable;
      this.formData.cityCode = obj[0].id;
      this.entCity_arr2 = obj[0].areaList;
    },
    entCity_change3(e, bool) {
      let obj = {};
      obj = this.entCity_arr2.filter(item => {
        return item.id === e;
      });
      if (obj.length !== 0) {
        this.formData.countyName = obj[0].lable;
        this.formData.countyCode = obj[0].id;
      }
    },

    // 分页
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
      this.page.pageSize = val;
      this.initData();
    },
    handleCurrentChange(val) {
      // console.log(`当前页: ${val}`);
      this.page.curPage = val;
      this.initData();
    }
    
  },
  computed: {
    ...mapState([
    ]),
    // ...mapGetters(["selectedIds"])
  },
  components: {
    adminTable,
  },
}

</script>